/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reports;

import avenue.MyWindowEvent;
import avenue.Session;
import avenue.Utils;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Date;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Vehicle;

public class CollectionsReportForm extends javax.swing.JFrame {

    /**
     * Creates new form CollectionsReport
     */
    public CollectionsReportForm() {
        initComponents();
        Utils.centerOnScreen(this);
        Utils.initTableState(jTable1);
        jDateFrom.setDate(Utils.beginOfThisMonth(new Date()));
        jDateTo.setDate(new Date());
        this.getRootPane().setDefaultButton(jBtnSearch);
        //checkControls();
        Utils.logUCstart(this);
    }

    // private void checkControls() {
    //    jBtnSearch.setEnabled(!(jTxtCard.getText().trim().equals("") && jTxtRegNumber.getText().trim().equals("")));
    //}
    private void showReport() {
        if (!Utils.acceptNumbersOnly(jTxtCard.getText())) {
            return;
        }

        //NO VEHICLE DATA
        if ((jTxtRegNumber.getText().trim().equals("") && jTxtCard.getText().trim().equals(""))) {
            collectionQuery = DBManager.em.createQuery("SELECT c FROM Collection c where c.stationId=:stationId and c.passTimestamp>=:dateFrom and c.passTimestamp<=:dateTo order by c.passTimestamp desc").setParameter("stationId", Session.loginUser.getStationId()).setParameter("dateFrom", jDateFrom.getDate()).setParameter("dateTo", jDateTo.getDate());
        } else {
            if (!jTxtRegNumber.getText().trim().equals("")) {
                Vehicle v = Utils.VehicleByRegNumber(jTxtRegNumber.getText().trim());
                if (v != null) {
                    jTxtCard.setText(String.format("%d", v.getCardId().getBarcode()));
                } else {
                    Utils.showMessage(null, Utils.msgNotDataForCriteria, Utils.msgDialogTitle, JOptionPane.WARNING_MESSAGE);
                    return;
                }
            }

            collectionQuery = DBManager.em.createQuery("SELECT c FROM Collection c where c.stationId=:stationId and c.cardId.barcode=:barcode and c.passTimestamp>=:dateFrom and c.passTimestamp<=:dateTo order by c.passTimestamp desc").setParameter("stationId", Session.loginUser.getStationId()).setParameter("barcode", Integer.parseInt(jTxtCard.getText())).setParameter("dateFrom", jDateFrom.getDate()).setParameter("dateTo", jDateTo.getDate());
        }


        java.util.Collection data = collectionQuery.getResultList();
        for (Object entity : data) {
            DBManager.em.refresh(entity);
        }
        collectionList.clear();
        collectionList.addAll(data);
        if (data.isEmpty()) {
            Utils.showMessage(null, Utils.msgNotDataForCriteria, Utils.msgDialogTitle, JOptionPane.WARNING_MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        collectionQuery = java.beans.Beans.isDesignTime() ? null : DBManager.em.createQuery("SELECT c FROM Collection c where c.cardId.barcode=-1");
        collectionList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(collectionQuery.getResultList());
        dateTimeRenderer1 = new avenue.DateTimeRenderer();
        jPanel1 = new javax.swing.JPanel();
        jTxtRegNumber = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTxtCard = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jDateFrom = new com.toedter.calendar.JDateChooser();
        jDateTo = new com.toedter.calendar.JDateChooser();
        jBtnSearch = new javax.swing.JButton();
        jBtnCancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        dateTimeRenderer1.setText("dateTimeRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ιστορικό Διελεύσεων");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jPanel1KeyReleased(evt);
            }
        });

        jTxtRegNumber.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTxtRegNumberKeyReleased(evt);
            }
        });

        jLabel4.setText("Έως:");

        jTxtCard.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTxtCardKeyReleased(evt);
            }
        });

        jLabel3.setText("Από:");

        jLabel1.setText("Αρ. κάρτας:");

        jLabel2.setText("ή  Αρ. κυκλοφορίας:");

        jBtnSearch.setText("Αναζήτηση");
        jBtnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnSearchActionPerformed(evt);
            }
        });

        jBtnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jBtnCancel.setText("Ακυρο");
        jBtnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTxtCard, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(17, 17, 17)
                .addComponent(jTxtRegNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jDateFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jDateTo, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jBtnSearch)
                .addGap(18, 18, 18)
                .addComponent(jBtnCancel)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jDateTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jDateFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jTxtRegNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnCancel)
                    .addComponent(jTxtCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jBtnSearch))
                .addContainerGap())
        );

        jTable1.setRowSelectionAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, collectionList, jTable1, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cardId.barcode}"));
        columnBinding.setColumnName("Αρ. κάρτας");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${passTimestamp}"));
        columnBinding.setColumnName("Ημερομηνία");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stationId.description}"));
        columnBinding.setColumnName("Σταθμός διέλευσης");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tollCollected}"));
        columnBinding.setColumnName("Ποσό διέλευσης");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setCellRenderer(null);
        jTable1.getColumnModel().getColumn(1).setCellRenderer(dateTimeRenderer1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void closeMe(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
    }
    private void jBtnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnSearchActionPerformed
        showReport();
    }//GEN-LAST:event_jBtnSearchActionPerformed

    private void jTxtCardKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtCardKeyReleased
        //checkControls();        // TODO add your handling code here:
        jTxtRegNumber.setText("");
    }//GEN-LAST:event_jTxtCardKeyReleased

    private void jPanel1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPanel1KeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_jPanel1KeyReleased

    private void jTxtRegNumberKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtRegNumberKeyReleased
        jTxtCard.setText("");
    }//GEN-LAST:event_jTxtRegNumberKeyReleased

    private void jBtnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCancelActionPerformed

        closeMe(false);
    }//GEN-LAST:event_jBtnCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CollectionsReportForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CollectionsReportForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CollectionsReportForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CollectionsReportForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CollectionsReportForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Collection> collectionList;
    private javax.persistence.Query collectionQuery;
    private avenue.DateTimeRenderer dateTimeRenderer1;
    private javax.swing.JButton jBtnCancel;
    private javax.swing.JButton jBtnSearch;
    private com.toedter.calendar.JDateChooser jDateFrom;
    private com.toedter.calendar.JDateChooser jDateTo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTxtCard;
    private javax.swing.JTextField jTxtRegNumber;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
